import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cart } from './cart.entity';
import { AddCartDto } from './dto/add-cart.dto';
import { UpdateCartDto } from './dto/update-cart.dto';
import { User } from '../user/user.entity';
import { Product } from '../product/product.entity';

@Injectable()
export class CartService {
  constructor(
    @InjectRepository(Cart)
    private readonly cartRepository: Repository<Cart>,
    @InjectRepository(Product)
    private readonly productRepository: Repository<Product>,
  ) {}

  async add(user: User, dto: AddCartDto): Promise<Cart> {
    const product = await this.productRepository.findOne({ where: { id: dto.productId } });
    if (!product) throw new NotFoundException('商品不存在');
    let cart = await this.cartRepository.findOne({ where: { user: { id: user.id }, product: { id: dto.productId } }, relations: ['user', 'product'] });
    if (cart) {
      cart.quantity += dto.quantity;
    } else {
      cart = this.cartRepository.create({ user, product, quantity: dto.quantity });
    }
    return this.cartRepository.save(cart);
  }

  async findAll(user: User): Promise<Cart[]> {
    return this.cartRepository.find({ where: { user: { id: user.id } }, relations: ['product'] });
  }

  async update(user: User, cartId: number, dto: UpdateCartDto): Promise<Cart> {
    const cart = await this.cartRepository.findOne({ where: { id: cartId, user: { id: user.id } }, relations: ['product'] });
    if (!cart) throw new NotFoundException('购物车项不存在');
    cart.quantity = dto.quantity;
    return this.cartRepository.save(cart);
  }

  async remove(user: User, cartId: number): Promise<void> {
    const cart = await this.cartRepository.findOne({ where: { id: cartId, user: { id: user.id } } });
    if (!cart) throw new NotFoundException('购物车项不存在');
    await this.cartRepository.remove(cart);
  }
}
